//yw 1初始化
layui.use(['form','layer','laydate','table','element'],function(){
    var $ = layui.jquery;
    var form = layui.form;
    var table= layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var element = layui.element;
    var schoolData = null;//yw 学校数据用于填充学校下拉框，防止反复从服务器下载学校数据
    var tBuildData = null;
     //yw 2显示列表
     var tableIns = table.render({
         elem: '#list',
         //url : '/user/queryUser',  //yw 按学校id,教学楼,姓名查询
         url : '/user/queryUserByName', //模糊查询
         cellMinWidth : 95,
         page : true,
         width : 1000,
         height : 670,
         limit : 15,
         limits : [15,10,20,30],
         id : "listTable",
         method:'get',
         cols : [[
             {field: 'userrealname', title: '教师姓名', width:100,align:'center'},
             {field: 'post', title: '职务', width:120,align:'center'},
             {field: 'usertel', title: '手机号码', width:140,align:'center'},
             {field: 'useraddtime', title: '添加时间', width:180, align:'center'},
             {field: 'tbuildname', title: '教学楼',width:120,align:'center'},
             {field: 'authcroomid', title: '授权教室',width:220,align:'center'},
             {fixed:"right",title: '操作', toolbar:'#listRowBar',align:"center"}
         ]]
     });

    //yw 3操作 1)模糊查询
    $(".search_btn").on("click",function(){
        tableIns.reload({
            page: {
                    curr: 1 //重新从第 1 页开始
            },
            //where:{
                //name: $(".searchVal").val() //yw 如果没有按学校和教学楼查询可以使用否则有两个name
            //},
            url:'/user/queryUserByName?name='+$(".searchVal").val()
            //url:'/user/queryUserByName'
        });
        return false;
    });

     //yw 3操作 2)新增 (a)打开添加的弹出层
    $(".add_btn").click(function(){
        mainIndex = layer.open({
            title : ['添加教师','font-size:18px;text-align:center;color:blue;'],
            type : 1, //yw 0.默认信息框,1.page,2.iframe,3.加载层,4.tips层
            content : $("#addDiv"),//yw ,$("#addDiv"),type:1 | "gatewayAdd.html", type:2
            area:['400px','490px'],
            offset:'r',
            success : function(){
                if(schoolData == null) {
                    $.ajax({ //yw 从后台获取学校数据，填充前端的学校下拉框
                        url:'/school/getAllSchoolName',
                        dataType:'json',
                        type:'post',
                        success:function(data2){
                            schoolData = data2;
                            $.each(data2,function(index,item){
                                $("#schoolId").append(new Option(item.name,item.id));
                            });
                            form.render("select");

                        }
                    })
                }else{
                    $("#schoolId").empty();
                    $.each(schoolData,function(index,item){
                        $("#schoolId").append(new Option(item.name,item.id));
                    });
                    form.render("select");
                }
            }
        })
    });
    //yw 3操作 2)新增 (b)提交监听事件--新增记录
    form.on("submit(doSubmitAdd)",function(){
        $.ajax({
            type:"post",
            url:"/user/addUser",
            data:{schoolid:$("#schoolId").val(),schoolname:$("#schoolId").find("option:selected").text(),userrealname:$("#userRealname").val(),username:$("#userName").val(),userpwd:$("#userPwd").val(),usertel:$("#userTel").val(),userremark:$("#userRemark").val()},
            success:function(res){
                if(res){
                    tableIns.reload();
                    layer.msg('新增成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                }else{
                    layer.msg('新增失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
                layer.closeAll('page'); //yw 关闭新增界面
            }
        });
    });

    //禁止表单回车提交
    $('form').on('keydown', function (event) {
        if (event.keyCode == 13) return false;
    })

    //yw 监听行工具条的事件
    table.on("tool(list)", function(obj){
        var   data = obj.data; //获得当前行数据
        switch(obj.event){
            case 'edit':
                openUpdateLayer(data);
                break;
            case 'del':
                deleteInfo(data);
                break;
        };
    });
    //yw 监听导航事件
    $("[name=t1]").click(function (){
        var name_v = $(".searchVal").val().trim();
        var schoolId_v =  $(this).attr("schoolId");
		// alert(schoolId_v);
        var tBuildName_v =  $(this).attr("tBuildName");
        var url_address = '/user/queryUser?schoolId='+schoolId_v+'&tBuildName='+tBuildName_v;
        if(name_v!=""){
            url_address = url_address+'&name='+name_v;
        }
        tableIns.reload({
            page: {
                    curr: 1 //重新从第 1 页开始
            },
            url : url_address, //模糊查询
        });
        return false;
    });
    //yw 3操作 3)更新  (a)打开修改的弹出层
    function openUpdateLayer(data){
        mainIndex = layer.open({
            title : ['修改教师','font-size:18px;text-align:center;color:blue;'],
            type : 1,
            content : $("#saveDiv"),
            area:['400px','540px'],
            offset:'r',
            success:function(layero,index){ //yw layero是弹出层对象layer object
                if(schoolData == null) {
                    $.ajax({ //yw 从后台获取学校数据，填充前端的学校下拉框
                        url:'/school/getAllSchoolName',
                        async:false, //yw 取消异步下载模式，否则shoolId2第一次打开没有数据，第二次打开才有数据
                        dataType:'json',
                        type:'post',
                        success:function(res){
                            schoolData = res;
                            $.each(schoolData,function(index,item){
                                $("#schoolId2").append(new Option(item.name,item.id));
                            });
                        }
                    })
                }else{
                    $("#schoolId2").empty();
                    $.each(schoolData,function(index,item){
                        $("#schoolId2").append(new Option(item.name,item.id));
                    });
                }
                 $("#userId").val(data.userid);
                 $("#schoolId2").val(data.schoolid);
                 form.render("select");//yw 给下拉框赋值要重新渲染一下下拉框或form.render();
                 $("#userTel2").val(data.usertel);
                 $("#userName2").val(data.username);
                 $("#userRealname2").val(data.userrealname);
                 //$("#tbuildName").val(data.tbuildname);
                 //
                 if(tBuildData == null){
                    $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
                        url:'/school/getAlltBuildNameID?schoolID='+$("#schoolId2").val(),
                        async:false,
                        dataType:'json',
                        type:'post',
                        success:function(res2){
                            tBuildData = res2;
                            $("#tbuildName").empty();
                            $.each(res2,function(index,item){
                                // console.log(item); //debug
                                // console.log(item.name); //debug
                                $("#tbuildName").append(new Option(item.tbuildname,item.tbuildname));
                            });
                        }
                    })
                }else{
                    $("#tbuildName").empty();
                    $.each(tBuildData,function(index,item){
                        $("#tbuildName").append(new Option(item.tbuildname,item.tbuildname));
                    });
                }
                 // console.log(data)
                $("#tbuildName").val(data.tbuildname);
                form.render("select");
                 $("#authcroomid").val(data.authcroomid);
                 $("#userState").val(data.userstate);
                 $("#post").val(data.post);
                 $("#userRemark2").val(data.userremark);
            }
        });
     }
     // var flag = false;
     //yw 改变学校下拉框的选项，填充教学楼下拉框 lay-filter="schoolId2"
     form.on("select(schoolId2)",function(){
        //alert("schoolId2");
        $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
            url:'/school/getAlltBuildNameID?schoolID='+$("#schoolId2").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
               tBuildData = res;
               //console.log(tBuildData);
               $("#tbuildName").empty();
               $.each(tBuildData,function(index,item){
                   //console.log(item); //debug
                   //console.log(item.name); //debug
                   $("#tbuildName").append(new Option(item.tbuildname,item.tbuildname));
               });
               form.render("select");
            }
        })
     });
         //yw 3操作 3)更新 (b)提交监听事件--修改记录
    form.on("submit(doSubmitSave)",function(){
        $.ajax({
            type:"post",
            url:"/user/saveUser",
            data:{userid:$("#userId").val(),schoolid:$("#schoolId2").val(),schoolname:$("#schoolId2").find("option:selected").text(),usertel:$("#userTel2").val(),userrealname:$("#userRealname2").val(),username:$("#userName2").val(),tbuildname:$("#tbuildName").val(),authcroomid:$("#authcroomid").val(),userstate:$("#userState").val(),post:$("#post").val(),userremark:$("#userRemark2").val()},
            success:function(res){
                if(res){
                    tableIns.reload();
                    layer.msg('保存成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                }else{
                    layer.msg('保存失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
                layer.closeAll('page'); //yw 关闭新增界面 type=1
            }
        });
    });
    //yw 3操作 4)删除
    function deleteInfo(data){
        layer.confirm('你确定要删除['+data.userrealname+']这条数据吗?',{icon:3,title:'提示'},function(index){
            $.ajax({
                type:"POST",
                url:'/user/delUser?userId='+data.userid,
                success:function(res){
                    if(res){
                        tableIns.reload();
                        layer.msg('删除成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                    }else{
                        layer.msg('删除失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                    }
                }
            });
            layer.close(index); //yw 关闭删除提示对话框
        });
    }

    //yw 表单验证
    form.verify({
        required: [/[\S]+/, "不能为空"],
        username:[/^[a-zA-Z0-9_-]{4,16}$/,"用户名4-16位字母数字下划线减号"],
        phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
        email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
        url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
        integer: [/^\d*$/, "只能填写整数"],
        date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
        identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"],
        // 校验两次密码是否一致
        userPwd: [/(.+){6,12}$/, '密码必须6到12位'],
        userPwdCheck:function(value){
            if($('input[name=userPwd]').val() !== value)
                return '两次密码输入不一致！';
        },
        number: function (e) {
            if (e && isNaN(e))return "只能填写数字"
        },
        lenLimit20:function(value){
            if(value.length>20) return '长度不能超过20个字符';
        },
        lenLimit50:function(value){
            if(value.length>20) return '长度不能超过50个字符';
        },
        lenLimit100:function(value){
            if(value.length>100) return '长度不能超过50个字符';
        }
    });
    //导航

}); //yw 最后一行对应layui.use(['form','layer','laydate','table'],function(){
